package com.ccp.dev.extend.service;

import com.ccp.dev.core.basic.consts.SystemConst;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.extend.dao.ExtendSysOrgDao;
import com.ccp.dev.extend.dao.ExtendSysUserDao;
import com.ccp.dev.system.dao.SysOrgDao;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.service.SysOrgService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 扩展的组织管理模块service
 *
 * @author 创新中心-王明亮
 */
@Service
public class ExtendSysOrgService {

    @Resource
    private SysOrgService sysOrgService;
    @Resource
    private SysOrgDao sysOrgDao;
    @Resource
    private ExtendSysOrgDao extendSysOrgDao;
    @Resource
    private ExtendSysUserDao extendSysUserDao;

    /**
     * 获取当前组织下的子单位
     * @return 单位集合
     */
    public List<Dictionary> getSubordinateUnits() {
        //取到当前单位
        SysOrg currentOrg = getTenOrg(ContextUtil.getCurrentUserId());
        List<SysOrg> sysOrgs = sysOrgDao.querySubOrgBySupId(currentOrg.getOrgId());
        List<SysOrg> subordinateUnits = sysOrgs.stream().filter(sysOrg -> sysOrg.getIsTenant() == 1).collect(Collectors.toList());
        List<Dictionary> dicList = new ArrayList<>();
        if(BeanUtils.isNotEmpty(subordinateUnits)){
            for (SysOrg sysOrg : subordinateUnits) {
                Dictionary dictionary = new Dictionary();
                dictionary.setItemName(sysOrg.getOrgName());
                dictionary.setItemValue(sysOrg.getCode());
                dicList.add(dictionary);
            }
        }
        return dicList;
    }

    /**
     * 查询组织树根节点下面的子（不包括孙）
     *
     * @return
     */
    public List<SysOrg> getSubLevelOrg() {
        List<SysOrg> sysOrgs = sysOrgDao.querySubOrgBySupId(SystemConst.TOP_ORG_ID);
        if (sysOrgs.size() == 0) {
            return sysOrgs;
        }
        return sysOrgDao.querySubOrgBySupId(sysOrgs.get(0).getOrgId());
    }

    /**
     * 根据租户id,查询对应的组织列表
     *
     * @param tenantId
     * @return
     */
    public List<SysOrg> getOrgsByTenId(String tenantId) {
        return extendSysOrgDao.getOrgsByTenantId(tenantId);
    }


    /**
     * 获取用户直属租户组织
     *
     * @param userId 用户id
     * @return SysOrg 用户所在直属租户组织
     * @author 创新中心-王明亮
     */
    public SysOrg getTenOrg(String userId) {
        String tenantId = ContextUtil.getCurrentUserTenantId(userId);
        return sysOrgDao.getOrgByTenantId(tenantId);
    }

    /**
     * 查询组织树根节点下面的子（不包括孙）并转成数据字典样式
     *
     * @return List<Dictionary>
     * @author 孙丰佳
     */
    public List<Dictionary> getOriginOrgToDicList() {
        List<SysOrg> sysOrgList = getSubLevelOrg();
        sysOrgList = sysOrgList.stream().filter(sysOrg -> sysOrg.getIsTenant() == 1).collect(Collectors.toList());
        List<Dictionary> dicList = new ArrayList<>();
        for (SysOrg sysOrg : sysOrgList) {
            Dictionary dictionary = new Dictionary();
            dictionary.setItemName(sysOrg.getOrgName());
            dictionary.setItemValue(sysOrg.getCode());
            dicList.add(dictionary);
        }
        return dicList;
    }

    /**
     * 根据租户查询列表
     * @param queryFilter 条件filter
     * @return list
     */
    public List<SysUser> listByTenTree(QueryFilter queryFilter) {
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        if (!queryFilter.containsKey("dataPrivacyLevel")) {
            int privacyLevel = sysUser.getPrivacyLevel();
            queryFilter.put("privacyLevel", privacyLevel);
        }
        List<String> tenantIds = new ArrayList<>();
        List<SysOrg> sysOrgList = new ArrayList<>();
        if(StringUtil.isEmpty(queryFilter.get("orgId"))&& !SystemConst.SUPER_ADMIN_ID.equals(sysUser.getUserId())){
            // 登录人所在租户
            String tenantId = ContextUtil.getCurrentUserTenantId(ContextUtil.getCurrentUserId());
            // 根据租户id查找组织
            SysOrg sysOrg = sysOrgService.getOrgByTenId(tenantId);
            // 根据组织id查找其所有子组织
            sysOrgList = this.querySubSysOrgBySupOrgId(sysOrg.getOrgId());
        }else if (StringUtil.isNotEmpty(String.valueOf(queryFilter.get("orgId")))){
            // 根据组织id查找其所有子组织
            sysOrgList = this.querySubSysOrgBySupOrgId(String.valueOf(queryFilter.get("orgId")));
        }
        // 取出所有组织的租户id放到集合中
        for (SysOrg sysOrg : sysOrgList) {
            String tenantId = sysOrgService.getTenantIdByOrgId(sysOrg.getOrgId());
            if (!tenantIds.contains(tenantId)){
                tenantIds.add(tenantId);
            }
        }
        // 加入租户id查询条件，去除组织id查询条件
        queryFilter.addFilter("tenantIds",tenantIds);
        queryFilter.remove("orgId");
        // 查询到的数据
        List<SysUser> sysUserList = extendSysUserDao.queryUsersByTenOrg(queryFilter);
        // 把所属单位是部门的循环遍历替换成租户组织
        for (SysUser user : sysUserList) {
            String orgId = user.getOrgId();
            int isTenant = sysOrgService.getOneById(orgId).getIsTenant();
            if (isTenant != 1){
                String tenantId = sysOrgService.getTenIdByOrgId(orgId);
                SysOrg sysOrg = sysOrgService.getOrgByTenId(tenantId);
                user.setOrgId(sysOrg.getOrgId());
                user.setOrgName(sysOrg.getOrgName());
            }
        }
        return sysUserList;
    }

    /**
     * 根据组织id查找其所有子组织
     * @param orgId 父id
     * @return 所有子租户和组织
     */
    public List<SysOrg> querySubSysOrgBySupOrgId(String orgId) {
        SysOrg org = sysOrgDao.getById(orgId);
        Map<String,String> map = new HashMap<>(2);
        map.put("orgId",orgId);
        map.put("pathLike",org.getPath()+ StringPool.PERCENT);
        List<SysOrg> childSysOrgList = sysOrgDao.querySubOrgByPath(map);
        return childSysOrgList;
    }

    /**
     * 获取当前用户所属单位的所有下级单位,并转成dic
     * 2020-8-19 问题责任单位使用
     * @author zzy
     * @return
     */
    public List<Dictionary> getAllSubUnits(){
        List<SysOrg> orgList = this.querySubSysOrgBySupOrgId(ContextUtil.getCurrentOrgId());
        List<Dictionary> dictList = orgList.stream().filter(org -> org.getIsTenant() == 1).map(org -> {
            Dictionary dictionary = new Dictionary();
            dictionary.setItemName(org.getOrgName());
            dictionary.setItemValue(org.getCode());
            return dictionary;
        }).collect(Collectors.toList());
        return dictList;
    }

}
